package com.example.component;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.messaging.handler.HandlerMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class AuthHandlerInterceptor implements HandlerInterceptor {

    @Resource
    JWTUtils jwtUtils;

    /**
     * 权限认证的拦截操作.
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        System.out.println("=======进入权限认证拦截器=======");

        // 读取请求头中的 jwt
        // 这里图方便没有加 Bearer 前缀
        String jwt = httpServletRequest.getHeader("Authorization");
        // 大部分异常情况都可以在解析时捕获
        Map<String, String> map = null;
        try {
            map = jwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            System.out.println("鉴权错误，拦截请求");
            return false;
        }

        String username = map.get("username");
        // 根据 userId 等解析出的属性执行相关操作
        System.out.println("鉴权成功，通过请求：" + username);
        return true;
    }
}

